package com.jinarusha.shareprayers;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class EditPrayerActivity extends Activity {
	private EditText titleText;
	private EditText bodyText;
	private Long rowId;
	private ListItemDbAdapter dBHelper;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dBHelper = new ListItemDbAdapter(this);
		dBHelper.open();

		setContentView(R.layout.prayer_edit);
		setTitle(R.string.edit_prayer);

		titleText = (EditText) findViewById(R.id.title);
		bodyText = (EditText) findViewById(R.id.body);

		Button confirmButton = (Button) findViewById(R.id.confirm);

		rowId = (savedInstanceState == null) ? null : (Long) savedInstanceState
				.getSerializable(ListItemDbAdapter.KEY_ROWID);
		if (rowId == null) {
			Bundle extras = getIntent().getExtras();
			rowId = extras != null ? extras
					.getLong(ListItemDbAdapter.KEY_ROWID) : null;
		}

		populateFields();

		confirmButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {

				setResult(RESULT_OK);
				finish();
			}

		});

	}

	private void populateFields() {
		if (rowId != null) {
			Cursor note = dBHelper.fetchNote(rowId);
			startManagingCursor(note);
			titleText.setText(note.getString(note
					.getColumnIndexOrThrow(ListItemDbAdapter.KEY_TITLE)));
			bodyText.setText(note.getString(note
					.getColumnIndexOrThrow(ListItemDbAdapter.KEY_BODY)));
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		saveState();
		outState.putSerializable(ListItemDbAdapter.KEY_ROWID, rowId);
	}

	@Override
	protected void onPause() {
		super.onPause();
		saveState();
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateFields();
	}

	private void saveState() {
		String title = titleText.getText().toString();
		String body = bodyText.getText().toString();

		if (rowId == null) {
			long id = dBHelper.createNote(title, body);
			if (id > 0) {
				rowId = id;
			}
		} else {
			dBHelper.updateNote(rowId, title, body);
		}
	}
}
